package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.util.Log
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.getPreviousDay
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserStress
import com.module.ble.repo.UserStressRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvertByStepsRelatedRecord
import com.module.ble.utils.common48DataConvertByStressRecord
import com.module.ble.utils.common48DataConvertToAverage
import com.module.ble.widget.StressBrokenLineChart
import com.module.overview.R
import java.util.Calendar
import kotlin.collections.map

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/10
 *
 * 描述：压力总结卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvPressureSummaryCardProvider(mCalendar: CalendarDay?,
                                    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_PRESSURE_SUMMARY,
                                    override val layoutId: Int = R.layout.overview_pressure_summary_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {


    var mCalendar = mCalendar
    private var curTime = mCalendar?.toCalendar()?.timeInMillis?:0

    private var tvEarlyMorningCk: TextView? = null
    private var tvMorningCk : TextView? = null
    private var tvAfternoonCk : TextView? = null
    private var tvEveningCk : TextView? = null

    private var tvRelaxationDuration : TextView? = null
    private var tvTheDayDuration : TextView? = null
    private var tvWeeksDuration : TextView? = null


    private var stressLineChart: StressBrokenLineChart? = null
    private var stressLineChart2 : StressBrokenLineChart? = null

    private var earlyMorningStr = ViewUtils.getString(R.string.common_rail_unit)
    private var morningStr  = ViewUtils.getString(R.string.common_rail_unit)
    private var afternoonStr  = ViewUtils.getString(R.string.common_rail_unit)
    private var eveningStr  = ViewUtils.getString(R.string.common_rail_unit)

    private var yesterdayEarlyMorningStr = ViewUtils.getString(R.string.common_rail_unit)
    private var yesterdayMorningStr  = ViewUtils.getString(R.string.common_rail_unit)
    private var yesterdayAfternoonStr  = ViewUtils.getString(R.string.common_rail_unit)
    private var yesterdayEveningStr  = ViewUtils.getString(R.string.common_rail_unit)

    var theDayRelax = 0L//放松总时长
    var theDayNormal = 0L//正常总时长
    var theDayMedium = 0L//中等总时长
    var theDayHigh = 0L//偏高总时长

    var yesterdayRelax = 0L//放松总时长
    var yesterdayNormal = 0L//正常总时长
    var yesterdayMedium = 0L//中等总时长
    var yesterdayHigh = 0L//偏高总时长

    val def48Result = mutableListOf<CusChartData>()
    var curDef48Time = 0L

    var theDayBeforePointsAverage = 0f
    var yesterdayBeforePointsAverage = 0f

    val timeRanges by lazy { TimeUtils.getDayStartTimestamps(curTime, 6) }// 获取前7天的时间范围（含今天）

    // 根据timeRanges分类出每天的对应数据 - 使用List<Pair>格式
    private val perDayPairs = mutableListOf<Pair<Long, MutableList<UserStress>>>()

    // 7天的每天步数48个区间数据 - 使用List<Pair>格式
    private val sevenDaysStep48Pairs = mutableListOf<Pair<Long, MutableList<CusChartData>>>()

    private var synthesisTheDayStep48List = mutableListOf<CusChartData>()
    private var synthesisSevenDaysStep48List = mutableListOf<CusChartData>()

    init {
        // 创建48个时间区间块的CusChartData数组
        def48Result.clear()
        val currentTimestamp = TimeUtils.getTimeDateLong()
        // 获取curTime当天的0点时间戳
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = currentTimestamp
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        val startOfDay = calendar.timeInMillis

        for (index in 0 until 48) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val intervalStartTime = startOfDay + timeOffset
            val intervalEndTime = startOfDay + timeOffset + (30 * 60 * 1000L) // 加30分钟作为结束时间

            def48Result.add(
                CusChartData(
                    createdTime = intervalStartTime,
                    endTime = intervalEndTime,
                    mValue = -1f,
                    minValue = 0f,
                    dayNum = 0
                )
            )
        }

        curDef48Time = def48Result.find { chartData ->
            currentTimestamp >= chartData.createdTime && currentTimestamp < chartData.endTime
        }?.createdTime ?: 0L
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        initDefData()
        getSevenDaysStress()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvEarlyMorningCk = viewHolder.getView(R.id.tvEarlyMorningCk)
        tvMorningCk = viewHolder.getView(R.id.tvMorningCk)
        tvAfternoonCk = viewHolder.getView(R.id.tvAfternoonCk)
        tvEveningCk = viewHolder.getView(R.id.tvEveningCk)

        tvRelaxationDuration = viewHolder.getView(R.id.tvRelaxationDuration)
        tvTheDayDuration = viewHolder.getView(R.id.tvTheDayDuration)
        tvWeeksDuration = viewHolder.getView(R.id.tvWeeksDuration)

        stressLineChart = viewHolder.getView(R.id.stressLineChart)
        stressLineChart2 = viewHolder.getView(R.id.stressLineChart2)

//        // 设置触摸监听
//        stressLineChart?.setOnStressPointTouchListener(object :
//            StressBrokenLineChart.OnStressPointTouchListener{
//            override fun onPointTouch(pointIndex: Int, value: Float, timeLabel: String) {
//                // 处理触摸事件
//                Log.d("StressChart", "时间: $timeLabel, 压力值: $value")
//            }
//
//        })

        tvEarlyMorningCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    SpanUtils.create()
                        .addForeColorSection(
                            "${ViewUtils.getString(R.string.common_pressure_relax_hint)}\n",
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .addForeColorSection(
                            earlyMorningStr,
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .setAbsSize(earlyMorningStr, 16)
                        .showIn(viewIt)

                    tvEarlyMorningCk?.isSelected = true
                    tvMorningCk?.isSelected = false
                    tvAfternoonCk?.isSelected = false
                    tvEveningCk?.isSelected = false
                    stressLineChart?.setSelectType(0)
                    stressLineChart2?.setSelectType(0)

                    tvRelaxationDuration?.let {tvRelaxationDurationIt->
                        val differenceValue = theDayRelax-yesterdayRelax
                        var differenceValueHint = ""
                        differenceValueHint = when{
                            differenceValue < 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_reduce_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"小于0"
                            differenceValue == 0L -> ViewUtils.getString(R.string.overview_stress_as_this_point_consistent_hint)//"等于0"
                            differenceValue > 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_add_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"大于0"
                            else -> {""}
                        }

                        SpanUtils.create()
                            .addSection(ViewUtils.getString(R.string.overview_stress_as_this_point_hint))
                            .addForeColorSection(
                                "${ViewUtils.getString(R.string.common_pressure_relax_duration_hint)}",
                                ViewUtils.getColor(R.color.c_5282ff)
                            )
                            .addSection(differenceValueHint)
                            .showIn(tvRelaxationDurationIt)
                    }
                    tvTheDayDuration?.text = "${if(mCalendar?.dateName == ViewUtils.getString(R.string.common_today_hint)) ViewUtils.getString(R.string.common_today_hint) else TimeUtils.getYearMonthDay4(curTime)}(${TimeUtils.getHourMinute(curDef48Time)}) $earlyMorningStr"
                    tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}(${TimeUtils.getHourMinute(curDef48Time)}) $yesterdayEarlyMorningStr"
                }
            }
        }

        tvMorningCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    SpanUtils.create()
                        .addForeColorSection(
                            "${ViewUtils.getString(R.string.common_pressure_normal_hint)}\n",
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .addForeColorSection(
                            morningStr,
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .setAbsSize(morningStr, 16)
                        .showIn(viewIt)

                    tvMorningCk?.isSelected = true
                    tvEarlyMorningCk?.isSelected = false
                    tvAfternoonCk?.isSelected = false
                    tvEveningCk?.isSelected = false
                    stressLineChart?.setSelectType(1)
                    stressLineChart2?.setSelectType(1)


                    tvRelaxationDuration?.let {tvRelaxationDurationIt->
                        val differenceValue = theDayNormal-yesterdayNormal
                        var differenceValueHint = ""
                        differenceValueHint = when{
                            differenceValue < 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_reduce_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"小于0"
                            differenceValue == 0L -> ViewUtils.getString(R.string.overview_stress_as_this_point_consistent_hint)//"等于0"
                            differenceValue > 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_add_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"大于0"
                            else -> {""}
                        }

                        SpanUtils.create()
                            .addSection(ViewUtils.getString(R.string.overview_stress_as_this_point_hint))
                            .addForeColorSection(
                                "${ViewUtils.getString(R.string.common_pressure_normal_duration_hint)}",
                                ViewUtils.getColor(R.color.c_5282ff)
                            )
                            .addSection(differenceValueHint)
                            .showIn(tvRelaxationDurationIt)
                    }
                    tvTheDayDuration?.text = "${if(mCalendar?.dateName == ViewUtils.getString(R.string.common_today_hint)) ViewUtils.getString(R.string.common_today_hint) else TimeUtils.getYearMonthDay4(curTime)}(${TimeUtils.getHourMinute(curDef48Time)}) $morningStr"
                    tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}(${TimeUtils.getHourMinute(curDef48Time)}) $yesterdayMorningStr"
                }
            }
        }

        tvAfternoonCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    SpanUtils.create()
                        .addForeColorSection(
                            "${ViewUtils.getString(R.string.common_pressure_medium_hint)}\n",
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .addForeColorSection(
                            afternoonStr,
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .setAbsSize(afternoonStr, 16)
                        .showIn(viewIt)

                    tvAfternoonCk?.isSelected = true
                    tvEarlyMorningCk?.isSelected = false
                    tvMorningCk?.isSelected = false
                    tvEveningCk?.isSelected = false
                    stressLineChart?.setSelectType(2)
                    stressLineChart2?.setSelectType(2)

                    tvRelaxationDuration?.let {tvRelaxationDurationIt->
                        val differenceValue = theDayMedium-yesterdayMedium
                        var differenceValueHint = ""
                        differenceValueHint = when{
                            differenceValue < 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_reduce_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"小于0"
                            differenceValue == 0L -> ViewUtils.getString(R.string.overview_stress_as_this_point_consistent_hint)//"等于0"
                            differenceValue > 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_add_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"大于0"
                            else -> {""}
                        }

                        SpanUtils.create()
                            .addSection(ViewUtils.getString(R.string.overview_stress_as_this_point_hint))
                            .addForeColorSection(
                                "${ViewUtils.getString(R.string.common_pressure_medium_duration_hint)}",
                                ViewUtils.getColor(R.color.c_5282ff)
                            )
                            .addSection(differenceValueHint)
                            .showIn(tvRelaxationDurationIt)
                    }
                    tvTheDayDuration?.text = "${if(mCalendar?.dateName == ViewUtils.getString(R.string.common_today_hint)) ViewUtils.getString(R.string.common_today_hint) else TimeUtils.getYearMonthDay4(curTime)}(${TimeUtils.getHourMinute(curDef48Time)}) $afternoonStr"
                    tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}(${TimeUtils.getHourMinute(curDef48Time)}) $yesterdayAfternoonStr"
                }
            }
        }

        tvEveningCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    SpanUtils.create()
                        .addForeColorSection(
                            "${ViewUtils.getString(R.string.common_pressure_high_hint)}\n",
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .addForeColorSection(
                            eveningStr,
                            ViewUtils.getColor(R.color.c_5282ff)
                        )
                        .setAbsSize(eveningStr, 16)
                        .showIn(viewIt)

                    tvEveningCk?.isSelected = true
                    tvEarlyMorningCk?.isSelected = false
                    tvMorningCk?.isSelected = false
                    tvAfternoonCk?.isSelected = false
                    stressLineChart?.setSelectType(3)
                    stressLineChart2?.setSelectType(3)

                    tvRelaxationDuration?.let {tvRelaxationDurationIt->
                        val differenceValue = theDayHigh-yesterdayHigh
                        var differenceValueHint = ""
                        differenceValueHint = when{
                            differenceValue < 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_reduce_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"小于0"
                            differenceValue == 0L -> ViewUtils.getString(R.string.overview_stress_as_this_point_consistent_hint)//"等于0"
                            differenceValue > 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_add_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"大于0"
                            else -> {""}
                        }

                        SpanUtils.create()
                            .addSection(ViewUtils.getString(R.string.overview_stress_as_this_point_hint))
                            .addForeColorSection(
                                "${ViewUtils.getString(R.string.common_pressure_high_duration_hint)}",
                                ViewUtils.getColor(R.color.c_5282ff)
                            )
                            .addSection(differenceValueHint)
                            .showIn(tvRelaxationDurationIt)
                    }
                    tvTheDayDuration?.text = "${if(mCalendar?.dateName == ViewUtils.getString(R.string.common_today_hint)) ViewUtils.getString(R.string.common_today_hint) else TimeUtils.getYearMonthDay4(curTime)}(${TimeUtils.getHourMinute(curDef48Time)}) $eveningStr"
                    tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}(${TimeUtils.getHourMinute(curDef48Time)}) $eveningStr"
                }
            }
        }

        setAllPillarNotSelect()

        super.onViewHolderCreated(viewHolder, viewType)
    }

    private fun setAllPillarNotSelect(){

        tvEarlyMorningCk?.let { viewIt ->
            SpanUtils.create()
                .addSection("${ViewUtils.getString(R.string.common_pressure_relax_hint)}\n")
                .addForeColorSection(
                    earlyMorningStr,
                    ViewUtils.getColor(R.color.text_content)
                )
                .setAbsSize(earlyMorningStr, 16)
                .showIn(viewIt)
        }
        tvMorningCk?.let { viewIt ->
            SpanUtils.create()
                .addSection("${ViewUtils.getString(R.string.common_pressure_normal_hint)}\n")
                .addForeColorSection(
                    morningStr,
                    ViewUtils.getColor(R.color.text_content)
                )
                .setAbsSize(morningStr, 16)
                .showIn(viewIt)
        }
        tvAfternoonCk?.let { viewIt ->
            SpanUtils.create()
                .addSection("${ViewUtils.getString(R.string.common_pressure_medium_hint)}\n")
                .addForeColorSection(
                    afternoonStr,
                    ViewUtils.getColor(R.color.text_content)
                )
                .setAbsSize(afternoonStr, 16)
                .showIn(viewIt)
        }
        tvEveningCk?.let { viewIt ->
            SpanUtils.create()
                .addSection("${ViewUtils.getString(R.string.common_pressure_high_hint)}\n")
                .addForeColorSection(
                    eveningStr,
                    ViewUtils.getColor(R.color.text_content)
                )
                .setAbsSize(eveningStr, 16)
                .showIn(viewIt)
        }
        tvEarlyMorningCk?.isSelected = false
        tvMorningCk?.isSelected = false
        tvAfternoonCk?.isSelected = false
        tvEveningCk?.isSelected = false
        stressLineChart?.setSelectType(-1)
        stressLineChart2?.setSelectType(-1)


        tvRelaxationDuration?.let {tvRelaxationDurationIt->
            val differenceValue = 0L
            var differenceValueHint = ""
            differenceValueHint = when{
                differenceValue < 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_reduce_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"小于0"
                differenceValue == 0L -> ViewUtils.getString(R.string.overview_stress_as_this_point_consistent_hint)//"等于0"
                differenceValue > 0L -> "${ViewUtils.getString(R.string.overview_stress_as_this_point_add_hint)}${TimeUtils.formatTime(differenceValue*(1000 * 60), showHour = true, showMin = true)}"//"大于0"
                else -> {""}
            }

            SpanUtils.create()
                .addSection(ViewUtils.getString(R.string.overview_stress_as_this_point_hint2))
                .addForeColorSection(
                    "${ViewUtils.getString(R.string.common_pressure_hint)}",
                    ViewUtils.getColor(R.color.c_5282ff)
                )
                .addSection(differenceValueHint)
                .showIn(tvRelaxationDurationIt)
        }
        tvTheDayDuration?.text = "${if(mCalendar?.dateName == ViewUtils.getString(R.string.common_today_hint)) ViewUtils.getString(R.string.common_today_hint) else TimeUtils.getYearMonthDay4(curTime)}(${TimeUtils.getHourMinute(curDef48Time)})  ${theDayBeforePointsAverage.toInt()}${ViewUtils.getString(R.string.common_score_hint)}"
        tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}(${TimeUtils.getHourMinute(curDef48Time)})  ${yesterdayBeforePointsAverage.toInt()}${ViewUtils.getString(R.string.common_score_hint)}"
    }

    private fun initDefData(){
        theDayRelax = 0L//放松总时长
        theDayNormal = 0L//正常总时长
        theDayMedium = 0L//中等总时长
        theDayHigh = 0L//偏高总时长

        yesterdayRelax = 0L//放松总时长
        yesterdayNormal = 0L//正常总时长
        yesterdayMedium = 0L//中等总时长
        yesterdayHigh = 0L//偏高总时长
    }

    private fun initDefUI(){
    }

    /**
     * 获取7天压力信息
     */
    fun getSevenDaysStress(){
        if (curTime <=0) return

        UserStressRepo.instance.findByMultiTimeRanges(timeRanges)?.let { originalListIt->
//            val originalListIt :List<UserStress> = JsonUtils.fromJsonList("[{\"createdTime\":1755878460000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755878460000,\"stress\":73},{\"createdTime\":1755879240000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879240000,\"stress\":80},{\"createdTime\":1755879300000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879300000,\"stress\":43},{\"createdTime\":1755879360000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879360000,\"stress\":46},{\"createdTime\":1755883020000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755883020000,\"stress\":51},{\"createdTime\":1755883080000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755883080000,\"stress\":52},{\"createdTime\":1755884280000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755884280000,\"stress\":55},{\"createdTime\":1755886860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755886860000,\"stress\":86},{\"createdTime\":1755888660000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755888660000,\"stress\":83},{\"createdTime\":1755892260000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755892260000,\"stress\":90},{\"createdTime\":1755892860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755892860000,\"stress\":20},{\"createdTime\":1755924120000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755924120000,\"stress\":52}]")
            if (originalListIt.isNullOrEmpty()) return

//                val listItStr = JsonUtils.toJson(originalListIt)

            perDayPairs.clear()
            // 初始化每天的数据列表
            timeRanges.forEach { dayTimestamp ->
                perDayPairs.add(Pair(dayTimestamp, mutableListOf()))
            }

            // 将数据分类到对应的天
            originalListIt.forEach { record ->
                perDayPairs.forEachIndexed { index, (dayTimestamp, dayRecords) ->
                    val dayEnd = dayTimestamp + 24 * 60 * 60 * 1000 - 1 // 当天23:59:59.999

                    if (record.createdTime in dayTimestamp..dayEnd) {
                        dayRecords.add(record)
                        return@forEach // 找到对应天后跳出循环
                    }
                }
            }

            calculateClassData()
        }
    }

    fun calculateClassData(){
        if (perDayPairs.isNullOrEmpty()) return
        sevenDaysStep48Pairs.clear()
        perDayPairs.forEach {perDayPairsIt->
            sevenDaysStep48Pairs.add(Pair(perDayPairsIt.first, (common48DataConvertByStressRecord(curTime = perDayPairsIt.first, originalList = perDayPairsIt.second).toMutableList())))
        }

        sevenDaysStep48Pairs.sortByDescending { it.first }//按时间排序（降序）

        //取7天里第一条的second就是当天数据
        synthesisTheDayStep48List.clear()
        sevenDaysStep48Pairs.isNullOrEmpty().no {
            synthesisTheDayStep48List.addAll(sevenDaysStep48Pairs[0].second)
        }

        val curTimePointIndex = calculateCurrentTimePointIndex()

        synthesisTheDayStep48List.isNotEmpty().yes {//计算当天数据
            synthesisTheDayStep48List.sortBy { it.createdTime }//按时间排序（升序）
            val groupedSleepDataStr = JsonUtils.toJson(synthesisTheDayStep48List)
//            val curTimeList = generateTimeIntervals()
//            val curTimeListStr = JsonUtils.toJson(curTimeList)

            synthesisTheDayStep48List.forEachIndexed { index, item ->
                (curTimePointIndex >= index).yes {
                    when(item.mValue.toInt()){
                        in 0..30 -> {//放松
                            theDayRelax+= 30
                        }
                        in 31..60 -> {//正常
                            theDayNormal+=30
                        }
                        in 61..80 -> {//中等
                            theDayMedium+=30
                        }
                        in 81..100 -> {//偏高
                            theDayHigh+=30
                        }
                        else -> {// 处理超出范围的情况
                        }
                    }
                }
            }

            //计算从groupedSleepData获取stressLineChart?.getBeforePointIndex()下标为止的所有mValue的平均值
            theDayBeforePointsAverage = if (synthesisTheDayStep48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisTheDayStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.average()
                    ?.toFloat() ?: 0f
            } else {
                0f
            }

            earlyMorningStr = if(theDayRelax >0 ) "${TimeUtils.formatTime(theDayRelax*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            morningStr = if(theDayNormal >0 ) "${TimeUtils.formatTime(theDayNormal*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            afternoonStr = if(theDayMedium >0 ) "${TimeUtils.formatTime(theDayMedium*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            eveningStr = if(theDayHigh >0 ) "${TimeUtils.formatTime(theDayHigh*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)

            //  通知图表更新数据
            stressLineChart?.setStressData(synthesisTheDayStep48List)

        }


        synthesisSevenDaysStep48List.clear()
        if (sevenDaysStep48Pairs.isNotEmpty()) {
            // 获取第一天的数据作为模板，确定有多少个时间区间（通常是48个）
            val templateList = sevenDaysStep48Pairs.firstOrNull()?.second
            templateList?.let { template ->
                // 为每个时间区间创建汇总数据
                for (index in template.indices) {
                    var totalValue = 0f

                    // 遍历所有天的数据，累加对应下标的mValue
                    sevenDaysStep48Pairs.forEach { dayPair ->
                        val dayData = dayPair.second
                        if (index < dayData.size) {
                            totalValue += dayData[index].mValue
                        }
                    }

                    // 创建汇总的CusChartData，使用第一天对应时间区间的时间信息作为模板
                    val templateData = template[index]
                    synthesisSevenDaysStep48List.add(
                        CusChartData(
                            createdTime = templateData.createdTime,
                            endTime = templateData.endTime,
                            mValue = totalValue, // 所有天对应时间区间的总和
                            minValue = 0f,
                            dayNum = templateData.dayNum,
                            exStr = totalValue.toInt().toString()
                        )
                    )
                }
            }

            synthesisSevenDaysStep48List.sortBy { it.createdTime }
            val synthesisDayStep48ListStr = JsonUtils.toJson(synthesisSevenDaysStep48List)

            val curTimePointIndex = calculateCurrentTimePointIndex()

            synthesisSevenDaysStep48List.forEach {
                when(it.mValue.toInt()){
                    in 0..30 -> {//放松
                        yesterdayRelax+= 30
                    }
                    in 31..60 -> {//正常
                        yesterdayNormal+=30
                    }
                    in 61..80 -> {//中等
                        yesterdayMedium+=30
                    }
                    in 81..100 -> {//偏高
                        yesterdayHigh+=30
                    }
                    else -> {// 处理超出范围的情况
                    }
                }
            }


            //计算从groupedSleepData获取stressLineChart?.getBeforePointIndex()下标为止的所有mValue的平均值
            yesterdayBeforePointsAverage = if (synthesisSevenDaysStep48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisSevenDaysStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.average()
                    ?.toFloat() ?: 0f
            } else {
                0f
            }

            yesterdayEarlyMorningStr = if(yesterdayRelax >0 ) "${TimeUtils.formatTime(yesterdayRelax*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            yesterdayMorningStr = if(yesterdayNormal >0 ) "${TimeUtils.formatTime(yesterdayNormal*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            yesterdayAfternoonStr = if(yesterdayMedium >0 ) "${TimeUtils.formatTime(yesterdayMedium*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)
            yesterdayEveningStr = if(yesterdayHigh >0 ) "${TimeUtils.formatTime(yesterdayHigh*(1000 * 60), showHour = true, showMin = true)}" else ViewUtils.getString(R.string.common_rail_unit)

            //  通知图表更新数据
            stressLineChart2?.setStressData(synthesisSevenDaysStep48List)
        }

        setAllPillarNotSelect()
    }

    /**
     * 生成一天中所有30分钟时间区间的列表
     * @return 包含48个时间区间字符串的列表
     */
    private fun generateTimeIntervals(): List<String> {
        val intervals = mutableListOf<String>()

        for (hour in 0..23) {
            // 格式化小时，确保是两位数
            val formattedHour = String.format("%02d", hour)

            // 添加当前小时的两个30分钟区间
            intervals.add("$formattedHour:00~$formattedHour:30")

            // 对于第二个区间，需要处理跨小时的情况
            val nextHour = if (hour == 23) "00" else String.format("%02d", hour + 1)
            intervals.add("$formattedHour:30~${if (hour == 23) "00" else nextHour}:00")
        }

        return intervals
    }

    /**
     * 根据当前时间戳计算对应的数据点索引
     * @return
     */
    private fun calculateCurrentTimePointIndex(): Int {
        val calendar = Calendar.getInstance()
        val currentHour = calendar.get(Calendar.HOUR_OF_DAY)
        val currentMinute = calendar.get(Calendar.MINUTE)

        // 计算当前时间对应的30分钟区间索引
        // 每小时有2个数据点（00:00, 00:30），总共48个点
        return  currentHour * 2 + if (currentMinute >= 30) 1 else 0
    }
}
